<template>
  <div class="q-pa-md">
    <div class="q-gutter-md" style="max-width: 100%">
      <q-input
        type="text"
        standout
        bottom-slots
        v-model="httpRequest.url"
        counter
        maxlength="1200"
        @keyup.enter="onSend()"
      >
        <template v-slot:before>
          <q-select
            outlined
            v-model="httpRequest.method"
            :options="httpOptions"
          />
        </template>
        <template v-slot:append>
          <q-icon
            v-if="httpRequest.url !== ''"
            name="close"
            @click="httpRequest.url = ''"
            class="cursor-pointer"
          />
        </template>

        <template v-slot:hint>
          {{ httpResponse.time_cost }} {{ httpResponse.body_len }}</template
        >
        <template v-slot:after>
          <q-btn round dense flat icon="send" @click="onSend()" />
        </template>
      </q-input>
    </div>
  </div>
  <div class="q-pa-md">
    <div class="q-gutter-y-md" style="max-width: 100%">
      请求
      <q-card>
        <q-tabs
          v-model="tab"
          dense
          no-caps
          class="text-grey"
          active-color="primary"
          indicator-color="primary"
          narrow-indicator
        >
          <q-tab name="headers" label="Headers" />
          <q-tab name="body" label="Body" />
        </q-tabs>
        <!-- header tabs -->
        <q-separator />
        <q-tab-panels v-model="tab" animated>
          <q-tab-panel name="headers">
            <div class="q-pa-md">
              <div class="row">
                <div class="col text-right">
                  <q-btn
                    flat
                    color="primary"
                    label="增加[键:值]"
                    @click="onHeader()"
                  />
                </div>
              </div>

              <div class="row" v-for="item in headers" :key="item.key">
                <div class="col">
                  <q-input v-model="item.key" />
                </div>
                <div class="col">
                  <q-input v-model="item.value" />
                </div>
              </div>
            </div>
          </q-tab-panel>

          <q-tab-panel name="body">
            <div class="q-gutter-y-md">
              <q-input v-model="httpRequest.body" filled type="textarea" />
            </div>
          </q-tab-panel>
        </q-tab-panels>
      </q-card>
    </div>
  </div>
  <div class="q-pa-md">
    <div class="q-gutter-y-md" style="max-width: 100%">
      响应
      <pre style="white-space: pre-line">{{ httpResponse.header }}</pre>
      <pre style="white-space: pre-line">{{ httpResponse.body }}</pre>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue";
import { invoke } from "@tauri-apps/api/tauri";
import { emitter, Endpoint } from "../boot/global_variable";

// 当前api的ID
const ID = ref("");
const workplaceID = ref("");
class Response {
  constructor() {
    this.body = "";
    this.body_len = "0.00 KB";
    this.header = new Map();
    this.message = "";
    this.status = 0;
    this.time_cost = "";
    this.version = "";
  }
}

class Request {
  constructor(name, method, url, header, body) {
    this.method = method;
    this.url = url;
    this.header = header;
    this.body = body;
    this.name = name;
  }
}

const tab = ref("body");

const httpResponse = ref(Response);
const httpOptions = ref(["GET", "POST", "DELETE"]);
const httpRequest = ref({
  workplace_id: "",
  name: "",
  url: "",
  method: "GET",
  header: {},
  body: "",
});

const headers = ref([
  { key: "Content-Type", value: "application/json;charset=utf-8" },
]);

const onHttpRequest = async function () {
  headers.value.forEach((x) => {
    if (x.key != "") {
      httpRequest.value.header[x.key] = x.value;
    }
  });
  console.log(httpRequest.value);
  httpResponse.value = Response;
  await invoke("http_cmd", { request: httpRequest.value })
    .then((data) => {
      httpResponse.value = data;
      console.log("[RESULT]=>", httpResponse.value);
    })
    .catch((error) => {
      alert(error);
      console.log("[ERROR]=>", error);
    });
};
const onSend = async function () {
  if (httpRequest.value.url == "") {
    return;
  }
  console.log("Invoke the command");
  // 1.发起http请求
  onHttpRequest();
  // 2.保存api
  const request = {
    url: Endpoint + "/api/v1/api/new",
    method: "POST",
    header: {
      "Content-Type": "application/json;charset=utf-8",
    },
    body: JSON.stringify({
      workplace_id: workplaceID.value,
      name: httpRequest.value.url,
      url: httpRequest.value.url,
      method: httpRequest.value.method,
      header: httpRequest.value.header,
      body: httpRequest.value.body,
    }),
  };
  console.log(request);
  await invoke("http_cmd", { request: request })
    .then((data) => {
      console.log("[RESULT]=>", data);
      const id = JSON.parse(data.body).message;
      httpRequest.value.id = id;
      emitter.emit("workplace_changed", workplaceID.value);
    })
    .catch((error) => {
      console.log("[ERROR]=>", error);
    });
};

const onLoadAPI = async (id) => {
  if (id == "") {
    httpRequest.value = {
      workplace_id: "",
      name: "",
      url: "",
      method: "GET",
      header: {},
      body: "",
    };
    return;
  }

  // 1. 加载 api
  const request = {
    url: Endpoint + "/api/v1/api/get",
    method: "POST",
    header: {
      "Content-Type": "application/json;charset=utf-8",
    },
    body: JSON.stringify({ id: id }),
  };
  console.log(request);
  await invoke("http_cmd", { request: request })
    .then((data) => {
      console.log("[RESULT]=>", data);
      httpRequest.value = JSON.parse(data.body);

      // 2. load
      onHttpRequest();
    })
    .catch((error) => {
      console.log("[ERROR]=>", error);
    });
};

const onHeader = () => {
  headers.value.push({ key: "Self-Header", value: "" });
  console.log(httpRequest.value.header);
};

onMounted(() => {
  // 订阅api事件
  emitter.on("node_changed", async (id) => {
    console.log("[node_changed:on]=>", id);
    onLoadAPI(id);
  });

  // 订阅workplace
  emitter.on("workplace_changed", async (wid) => {
    workplaceID.value = wid;
  });
});

onUnmounted(() => {
  emitter.off("node_changed");
  emitter.off("workplace_changed");
});
</script>
